import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import {
  ArticleSourceInfoEditDto,
  ArticleSourceInfoServiceProxy,
  CreateOrUpdateArticleSourceInfoDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'create-or-edit-articleSourceDrawer',
  templateUrl: './create-or-edit-article-source.component.html',
  styleUrls: ['./create-or-edit-article-source.component.less'],
})
export class CreateOrEditArticleSourceComponent extends AppComponentBase {
  @Input() id?: number;
  altricleSourceForm: FormGroup;
  isLoadingBtn = false;

  articleSource: ArticleSourceInfoEditDto = new ArticleSourceInfoEditDto();

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private articleSourceService: ArticleSourceInfoServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.altricleSourceForm = this.fb.group({
      name: [null, [Validators.required]],
    });

    this.articleSourceService
      .getArticleSourceInfoForEdit(this.id)
      .subscribe(result => {
        this.articleSource = result.articleSourceInfo;
      });
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm() {
    for (const i in this.altricleSourceForm.controls) {
      this.altricleSourceForm.controls[i].markAsDirty();
      this.altricleSourceForm.controls[i].updateValueAndValidity();
    }
    if (this.altricleSourceForm.valid) {
      this.isLoadingBtn = true;
      const input = new CreateOrUpdateArticleSourceInfoDto();
      input.articleSourceInfo = this.articleSource;
      this.articleSourceService
        .createOrUpdateArticleSourceInfo(input)
        .pipe(finalize(() => (this.isLoadingBtn = false)))
        .subscribe(() => {
          this.notify.success('操作成功！');
          this.drawerRef.close(true);
        });
    }
  }
}
